<template>
  <div class="face-login">
    <NavBarView />
    <div style="text-align: center; line-height: 50px; margin-top: 50px">
      <!-- 主页面容器，红色背景，居中显示 -->
      <div
        ref="wrapper"
        class="w-full h-full bg-red flex flex-col items-center"
      >
        <!-- 视频元素容器 -->
        <video
          ref="videoEl"
          style="border-radius: 50%; width: 200px; height: 200px"
          autoplay
          muted
          playsinline
        />
        <div v-if="loading" class="loading-overlay">
          <el-icon class="el-icon-loading"></el-icon>
        </div>
      </div>
      <el-button
        @click="shoot()"
        style="
          background-color: blue;
          color: white;
          width: 250px;
          height: 40px;
          margin-top: 30px;
        "
        >登录</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import NavBarView from "./components/NavBarView.vue";
import { useRouter } from "vue-router";
import { checkCamera } from "./utils/camera";
import { captureImage } from "./utils/image";
import { ElMessage } from "element-plus";
import { facelogin } from "./services/faceLogin";
const router = useRouter();
const loading = ref(false);
const wrapper = ref<HTMLDivElement | null>(null);
const videoEl = ref<HTMLVideoElement | null>(null);

async function initCamera() {
  loading.value = true;
  try {
    await checkCamera(videoEl);
  } catch (error) {
    ElMessage.error((error as Error).message);
  } finally {
    loading.value = false;
  }
}

function shoot() {
  if (!videoEl.value || !wrapper.value) return;
  const imageDataUrl = captureImage(videoEl);
  submitImages(imageDataUrl);
}

async function submitImages(img: string) {
  loading.value = true;
  try {
    const res: any = await facelogin({ b64: img });
    if (res.code === 200) {
      ElMessage.success("面部识别成功");
      localStorage.setItem("accessToken", res.accessToken);
      localStorage.setItem("refreshToken", res.refreshToken);
      localStorage.setItem("user", JSON.stringify(res.user));
      router.push({ path: "/me" });
    }
  } catch (error) {
    ElMessage.error("人脸识别失败，请重试");
  } finally {
    loading.value = false;
  }
}
onMounted(() => {
  initCamera();
});
</script>

<style scoped lang="scss">
.face-login {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.el-icon-loading {
  font-size: 24px;
  color: #409eff;
}
</style>